// 本地存储工具函数

/**
 * 从 localStorage 获取字符串值
 * @param {string} key 
 * @returns {string|null}
 */
function getItem(key) {
    try {
        return localStorage.getItem(key);
    } catch (error) {
        console.warn('localStorage getItem 失败:', error);
        return null;
    }
}

/**
 * 设置 localStorage 字符串值
 * @param {string} key 
 * @param {string} value 
 */
function setItem(key, value) {
    try {
        localStorage.setItem(key, value);
    } catch (error) {
        console.warn('localStorage setItem 失败:', error);
    }
}

/**
 * 从 localStorage 删除项
 * @param {string} key 
 */
function removeItem(key) {
    try {
        localStorage.removeItem(key);
    } catch (error) {
        console.warn('localStorage removeItem 失败:', error);
    }
}

/**
 * 从 localStorage 获取 JSON 对象
 * @param {string} key 
 * @param {any} defaultValue 默认值
 * @returns {any}
 */
function getJSON(key, defaultValue = null) {
    try {
        const value = localStorage.getItem(key);
        return value ? JSON.parse(value) : defaultValue;
    } catch (error) {
        console.warn('localStorage getJSON 失败:', error);
        return defaultValue;
    }
}

/**
 * 设置 localStorage JSON 对象
 * @param {string} key 
 * @param {any} value 
 */
function setJSON(key, value) {
    try {
        localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
        console.warn('localStorage setJSON 失败:', error);
    }
}

/**
 * 清空所有 localStorage 数据
 */
function clear() {
    try {
        localStorage.clear();
    } catch (error) {
        console.warn('localStorage clear 失败:', error);
    }
}

/**
 * 获取所有 localStorage 键
 * @returns {string[]}
 */
function getAllKeys() {
    try {
        return Object.keys(localStorage);
    } catch (error) {
        console.warn('localStorage getAllKeys 失败:', error);
        return [];
    }
}

export {
    getItem,
    setItem,
    removeItem,
    getJSON,
    setJSON,
    clear,
    getAllKeys
};